package com.yeskery.nut.bean.condition;

import com.yeskery.nut.annotation.condition.ConditionalOnProfile;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 环境条件判断
 * @author sunjay
 * 2023/9/6
 */
public class OnProfileCondition implements Condition {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(OnProfileCondition.class.getName());

    /** 取反符号 */
    private static final String REVERS_SYMBOL = "!";

    @Override
    public boolean matches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata, Object conditionalAnnotation) {
        ConditionalOnProfile conditionalOnProfiles = (ConditionalOnProfile) conditionalAnnotation;
        for (String value : conditionalOnProfiles.value()) {
            String profile = value.trim();
            boolean reverse = false;
            if (profile.startsWith(REVERS_SYMBOL)) {
                profile = profile.substring(1);
                reverse = true;
            }
            boolean result = nutApplication.getNutConfigure().getEnvironment().getEnvName().equals(profile);
            if (reverse) {
                result = !result;
            }
            if (!result) {
                if (logger.isLoggable(Level.FINEST)) {
                    logger.log(Level.FINEST, "Profile Condition Not Match, Condition[" + this.getClass().getName()
                            + "], Expect Profile[" + profile
                            + "], Actual Profile[" + nutApplication.getNutConfigure().getEnvironment().getEnvName() + "]");
                }
                return false;
            }
        }
        return true;
    }
}
